<?php

namespace app\common\entity;

use think\Db;
use think\Model;

class TeamUser extends Model {

    protected $createTime = 'register_time';

    /**
     * @var string 对应的数据表名
     */
    protected $table = 'team_user';
    protected $auto = ['create_time'];

    //返回原有数据  不自动进行时间转换
    public function getCreateTimeAttr($time) {
        return $time;
    }

    public function add($tid, $uid) {
        $this->tid = $tid;
        $this->uid = $uid;
        $this->create_time = date('Y-m-d H:i:s', time());

        return $this->save();
    }

    /**
     * 获取列表
     * @param type $tid   公会列表
     * @param type $page    页数
     * @param type $tuid    会长id
     */
    public function getList($tid, $page, $tuid) {
        $page = max($page, 1);
        $limit = 30;
        $startLimit = ($page - 1) * $limit;

        $list = $this->where('tid', $tid)->where('uid', 'NEQ', $tuid)->limit($startLimit, $limit)->order('id DESC')->select();
        if (count($list)) {
            $list = $list->toArray();
            $uids = array_column($list, 'uid');
            $userModel = new User();
            $userInfo = $userModel->getUserInfoByUids($uids, 'nick_name,avatar,register_time');
            foreach ($list as $k => $v) {
                $tmpUser = $userInfo[$v['uid']] ? $userInfo[$v['uid']] : [];
                $list[$k]['avatar'] = isset($tmpUser['avatar']) ? $tmpUser['avatar'] : '/static/image/headphoto.jpg';
                $list[$k]['username'] = isset($tmpUser['nick_name']) ? $tmpUser['nick_name'] : '';
                $list[$k]['register_time'] = isset($tmpUser['register_time']) ? date('Y-m-d H:i:s', $tmpUser['register_time']) : '';
                $list[$k]['product_count'] = $userModel->productCount($v['uid']);
            }
        }
        $nextPage = ++$page;
        if (count($list) < $limit) {
            $nextPage = 0;
        }
        $data['list'] = $list;
        $data['nextPage'] = $nextPage;
        return $data;
    }

}
